package com.powroznik.tracker.client.android;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TrackerService1 ts1;

	private ServiceConnection serviceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName name, IBinder service) {
			ts1 = ((TrackerService1.TrackerService1Binder) service)
					.getService();
		}

		public void onServiceDisconnected(ComponentName name) {
			ts1 = null;
		}
	};

	private Timer timer = new Timer();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Log.w("MainActivity", "onCreate");
		sendBroadcast(new Intent(this, TrackerBroadcastReceiver.class));
		if (!bindService(new Intent(getBaseContext(), TrackerService1.class),
				serviceConnection, Context.BIND_AUTO_CREATE)) {
			throw new RuntimeException();
		}
		final Handler handler = new Handler();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				handler.post(new Runnable() {
					public void run() {
						TextView textView = (TextView) findViewById(R.id.textViewDeviceKey);
						if (ts1 != null) {
							StringBuffer sb = new StringBuffer();
							sb.append("The tracking code of your device is: ");
							sb.append(ts1.getDevice(false) != null ? ts1
									.getDevice(false).getCode1() : "???");
							sb.append(".\n");
							sb.append("\n");
							sb.append("Please go to http://www.powroznik.com.");
							sb.append("\n");
							sb.append("\n");
							sb.append("Buffer size = ");
							sb.append(ts1.getBufferSize());
							sb.append("\n");
							sb.append("\n");
							sb.append(ts1.getLog());
							textView.setText(sb);
						} else {
							textView.setText("Please wait...");
						}
					}
				});
			}
		}, 0, 3 * 1000);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		Log.w("MainActivity", "onDestroy");
		timer.cancel();
		unbindService(serviceConnection);
	}
}
